package com.licq.hongmeng.net;


import ohos.app.Context;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * SSL
 */
public class SSLSocketFactoryUtils {

    // /////////////////////////////以下是单向认证的配置方式//////////////////////////////////
    /**
     * 单向认证
     */
    public static SSLSocketFactory getOnewaySSLSocketFactory() {
        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            X509TrustManager tm = null;
            try {
                tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain,
                                                   String authType) throws CertificateException {
                        // do nothing，接受任意客户端证书
                    }

                    public void checkServerTrusted(X509Certificate[] chain,
                                                   String authType) throws CertificateException {
                        // do nothing，接受任意服务端证书
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                };
            } catch (Exception e) {
            }
            sslContext.init(null,
                    new TrustManager[]{tm},
                    new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {

        }
        return sslSocketFactory;
    }






    // /////////////////////////////以下是双向认证需要证书的配置方式//////////////////////////////////

    private final static String CLIENT_PRI_KEY = "client.bks";
    private final static String TRUSTSTORE_PUB_KEY = "server.bks";
    private final static String CLIENT_BKS_PASSWORD = "password";
    private final static String TRUSTSTORE_BKS_PASSWORD = "password";
    private final static String KEYSTORE_TYPE_BKS = "BKS";
    private static final String KEY_STORE_TYPE_P12 = "PKCS12";
    private final static String PROTOCOL_TYPE = "SSL";
    private final static String CERTIFICATE_FORMAT = "X509";
    private static final String SCHEME_HTTPS = "https";
    private static final int HTTPS_PORT = 8444;

    /**
     * 双向认证
     */
    public static SSLSocketFactory getTwowaySSLCertifcation(Context context)
            throws KeyStoreException, IOException, NoSuchAlgorithmException,
            CertificateException, UnrecoverableKeyException,
            KeyManagementException {
        SSLSocketFactory sslSocketFactory = null;
        // 服务器端需要验证的客户端证书，其实就是客户端的keystore
//        InputStream ksIn = context.getAssets().open(CLIENT_PRI_KEY);
//        InputStream tsIn = context.getAssets().open(TRUSTSTORE_PUB_KEY);// 加载证书
//        KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE_BKS);// 客户端信任的服务器端证书
//        KeyStore trustStore = KeyStore.getInstance(KEYSTORE_TYPE_BKS);// 读取证书
//        keyStore.load(ksIn, CLIENT_BKS_PASSWORD.toCharArray());
//        trustStore.load(tsIn, TRUSTSTORE_BKS_PASSWORD.toCharArray());
//        ksIn.close();
//        tsIn.close();
        // 初始化SSLContext
        SSLContext sslContext = SSLContext.getInstance(PROTOCOL_TYPE);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(CERTIFICATE_FORMAT);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(CERTIFICATE_FORMAT);
//        trustManagerFactory.init(trustStore);
//        keyManagerFactory.init(keyStore, CLIENT_BKS_PASSWORD.toCharArray());
        sslContext.init(keyManagerFactory.getKeyManagers(),
                trustManagerFactory.getTrustManagers(), null);
        sslSocketFactory = sslContext.getSocketFactory();
        return sslSocketFactory;
    }

    /**
     * host
     * */
    public static class AppHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;// 自行添加判断逻辑，true->Safe，false->unsafe
        }
    }

}
